<?php
/**
 * 外发
 */
namespace app\mp\home;
use app\common\controller\Common;
use app\common\service\FactoryOutgo as FactoryOutgoService;
use app\common\service\Order as OrderService;
use app\common\service\OrderSize as OrderSizeService;
use think\Db;

class Outgo extends Common
{
	protected $factoryOutgoId = 0;

	public function initialize() {
		parent::initialize();

		$this->view->engine->layout('layout_full');

		$code = $this->request->param('code/s');
		$factoryOutgoInfo = (new FactoryOutgoService())->getInfoByCode($code);
		if (!$factoryOutgoInfo) {
			header('content-type:text/html;charset=utf-8');
			header('HTTP/1.1 401 Unauthorized');
			exit('无权限访问');
		} elseif ($factoryOutgoInfo && $factoryOutgoInfo['status'] == 0) {
			header('content-type:text/html;charset=utf-8');
			header('HTTP/1.1 403 Forbidden');
			exit('该链接已禁止访问');
		}
		$this->factoryOutgoId = $factoryOutgoInfo['id'];
		$this->assign('factoryOutgoId', $factoryOutgoInfo['id']);
		$this->assign('factoryOutgoName', $factoryOutgoInfo['name']);
		$this->assign('code', $code);

		$this->assign('hisiCurMenu', ['title' => '']);
		$this->assign('hisiHead', '');
	}

	/**
	 * 输出layui的json数据
	 *
	 * @param array $data
	 * @param integer $count
	 * @return void
	 */
	protected function Json($code=1, $msg='', $data=[], $count=0)
	{
		if (empty($msg)) {
			$msg = $code == 1 ? '操作成功' : '操作失败';
		}
		return json(['code' => $code, 'msg' => $msg, 'data' => $data, 'count' => $count]);
	}

	/**
	 * 未完成列表
	 */
    public function index()
    {
    	$this->assign('hisiCurMenu', ['title' => '未完成订单']);
    	if ($this->request->isPost()) {
    		$where = [];
    		$where[] = ['outgo_status', '>', 0];
    		$where[] = ['outgo_over_time', '=', 0];
    		$where[] = ['factory_outgo_id', '=', $this->factoryOutgoId];
    		$list = db('order')->where($where)->order('outgo_time asc')->select();
    		$skus = array_column($list, 'sku');
    		$skuKV = db('sku')->where('sku', 'in', $skus)->column('ori_pic', 'sku');

    		$key = 'list';
    		$result = [
    			$key . '_orders' => count($list),
    			$key . '_items' => array_sum(array_column($list, 'quantity')),
    		];
    		$factoryKV = [0 => '未分配'] + getFactoryKV(true);
    		foreach ($list as $v) {
    			$result[$key][] = [
    				'client_ordernum' => $v['client_ordernum'],
    				'sku' => $v['sku'],
    				'quantity' => $v['quantity'],
    				'outgo_time' => '【发】'.date("n月j日", $v['outgo_time']),
    				'shipment_time' => '【交】'.date("n月j日", $v['shipment_time']-2*86400),
    				'pic' => arrayGet($skuKV, $v['sku'], ''),
    				'factory_name' => arrayGet($factoryKV, $v['factory_id'], ''),
    			];
    		}

    		return $this->Json(1, '', $result);
    	}

    	$this->assign('t', 1);
        return $this->fetch();
    }

    /**
     * 已完成列表
     */
    public function over()
    {
    	$t = $this->request->param('t/d', 1);
    	$timeRange = [
    		'1' => ['s' => strtotime(date('Y-m-d 00:00:00', time())), 'e' => time()],
    		'2' => ['s' => strtotime(date('Y-m-d 00:00:00', time()-86400)), 'e' => strtotime(date('Y-m-d 00:00:00', time()))-1],
    		'3' => ['s' => strtotime(date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")))), 'e' => time()],
    		'4' => ['s' => strtotime(date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1-7,date("Y")))), 'e' => strtotime(date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7-7,date("Y"))))],
    		'5' => ['s' => strtotime(date('Y-m-01 00:00:00', time())), 'e' => time()],
    		'6' => ['s' => mktime(0,0,0,date('n')-1,1,date('Y')), 'e' => strtotime(date('Y-m-01 00:00:00', time()))-1],
    	];
    	if (!array_key_exists($t, $timeRange)) $t=1;
    	$this->assign('t', $t);

    	$this->assign('hisiCurMenu', ['title' => '已完成订单']);
    	if ($this->request->isPost()) {
    		$where = [];
    		$where[] = ['outgo_status', '>', 0];
    		$where[] = ['outgo_over_time', 'between', [$timeRange[$t]['s'], $timeRange[$t]['e']]];
    		$where[] = ['factory_outgo_id', '=', $this->factoryOutgoId];
    		$list = db('order')->where($where)->order('outgo_over_time desc')->select();
    		$skus = array_column($list, 'sku');
    		$skuKV = db('sku')->where('sku', 'in', $skus)->column('ori_pic', 'sku');

    		$key = 'list';
    		$result = [
    			$key . '_orders' => count($list),
    			$key . '_items' => array_sum(array_column($list, 'quantity')),
    		];
    		$factoryKV = [0 => '未分配'] + getFactoryKV(true);
    		foreach ($list as $v) {
    			$result[$key][] = [
    				'client_ordernum' => $v['client_ordernum'],
    				'sku' => $v['sku'],
    				'quantity_text' => $v['quantity'] . '*' . $v['outgo_price'] . '=' . round($v['quantity'] * $v['outgo_price'], 2),
    				'outgo_over_time' => '【回】'.date("n月j日", $v['outgo_over_time']),
    				'shipment_time' => '【交】'.date("n月j日", $v['shipment_time']-2*86400),
    				'pic' => arrayGet($skuKV, $v['sku'], ''),
    				'factory_name' => arrayGet($factoryKV, $v['factory_id'], ''),
    			];
    		}

    		return $this->Json(1, '', $result);
    	}
    	return $this->fetch();
    }

    /**
     * 标记已完成状态（进入尾部）
     *
     * @author KING
     * @date 2020年7月1日
     *
     */
    public function done() {
    	$clientOrdernum = $this->request->post("client_ordernum", '');

    	$orderService = new OrderService();
    	$orderInfo = $orderService->getInfoByClientOrdernum($clientOrdernum);
    	if ($orderInfo) {
    		$upData = [];

    		if ($orderInfo['outgo_over_time'] > 0) {
    			return $this->Json(0, "订单已完成，请勿重复操作！");
    		}

    		if ($orderInfo['caigou_status'] == 0) {
    			$upData['caigou_status'] = 1;
    			$upData['caigou_over_time'] = time()-2;
    		}
    		if ($orderInfo['caichuang_status'] == 0) {
    			$upData['caichuang_status'] = 1;
    			$upData['caichuang_over_time'] = time()-1;
    		}
    		if ($orderInfo['chejian_status'] == 0) {
    			$upData['chejian_status'] = 1;
    			$upData['chejian_over_time'] = time();
    		}

    		$upData['outgo_over_time'] = time();
    		$orderService->updateInfo($upData, ["factory_outgo_id" => $this->factoryOutgoId, "client_ordernum" => $clientOrdernum]);

    		// 外发交回数等于实裁数
    		(new OrderSizeService())->updateInfo(['jiaohuo_count' => Db::raw('shicai_count')], ['order_id' => $orderInfo['id']]);

    		$this->addOrderLog(0, $clientOrdernum, '外发完成（车间完成），进入尾部');
    		return $this->Json(1, "操作成功！");
    	} else {
    		return $this->Json(0, "订单不存在，操作失败！");
    	}
    }

    /**
     * 添加订单日志
     *
     * @author KING
     * @date 2020年7月25日
     *
     * @param integer $orderId			订单ID
     * @param string $clientOrdernum	订单号
     * @param string $remark			备注
     * @return boolean
     */
    private function addOrderLog($orderId, $clientOrdernum, $remark) {
    	if (empty($orderId) && empty($clientOrdernum)) return false;
    	if (empty($orderId)) {
    		$orderId = db('order')->where('client_ordernum', $clientOrdernum)->value('id', 0);
    	} elseif (empty($clientOrdernum)) {
    		$clientOrdernum = db('order')->where('id', $orderId)->order('id desc')->value('client_ordernum', '');
    	}
    	$user = session('admin_user');
    	$logData = [
    		'uid' => arrayGet($user, 'uid', 0),
    		'order_id' => $orderId,
    		'client_ordernum' => $clientOrdernum,
    		'url' => $this->request->url(),
    		'module' => request()->module(),
    		'controller' => request()->controller(),
    		'action' => request()->action(),
    		'param' => json_encode($this->request->param()),
    		'remark' => $remark,
    		'ip' => $this->request->ip(),
    		'create_time' => time(),
    	];
    	db('order_log')->insert($logData);
    	return true;
    }
}